package cn.iocoder.yudao.module.system.controller.admin.gugu;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.MajorRecommendReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.MajorRecommendRespVO;
import cn.iocoder.yudao.module.system.service.gugu.MajorRecommendationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 管理后台 - 智能推荐专业控制器
 *
 * @author 芋道源码
 */
@Tag(name = "管理后台 - 智能推荐专业")
@RestController
@RequestMapping("/system/major-recommendation")
@Validated
@Slf4j
public class MajorRecommendationController {

    @Resource
    private MajorRecommendationService majorRecommendationService;

    @PostMapping("/recommend")
    @Operation(summary = "智能推荐专业")
    @PreAuthorize("@ss.hasPermission('system:major-recommendation:query')")
    public CommonResult<MajorRecommendRespVO> recommendMajors(@Valid @RequestBody MajorRecommendReqVO reqVO) {
        log.info("智能推荐专业请求：{}", reqVO);
        
        try {
            MajorRecommendRespVO result = majorRecommendationService.recommendMajors(reqVO);
            return success(result);
        } catch (Exception e) {
            log.error("智能推荐专业失败", e);
            return CommonResult.error(500, "推荐服务异常：" + e.getMessage());
        }
    }

    @PostMapping("/recommend-with-user")
    @Operation(summary = "智能推荐专业（带用户ID）")
    @PreAuthorize("@ss.hasPermission('system:major-recommendation:query')")
    public CommonResult<MajorRecommendRespVO> recommendMajorsWithUser(
            @Valid @RequestBody MajorRecommendReqVO reqVO,
            @Parameter(description = "用户ID") @RequestParam(required = false) Long userId) {
        log.info("智能推荐专业请求（用户ID：{}）：{}", userId, reqVO);
        
        try {
            MajorRecommendRespVO result = majorRecommendationService.recommendMajors(reqVO, userId);
            return success(result);
        } catch (Exception e) {
            log.error("智能推荐专业失败", e);
            return CommonResult.error(500, "推荐服务异常：" + e.getMessage());
        }
    }

    @GetMapping("/calculate-probability")
    @Operation(summary = "计算专业录取概率")
    @PreAuthorize("@ss.hasPermission('system:major-recommendation:query')")
    public CommonResult<Double> calculateMajorAdmissionProbability(
            @Parameter(description = "用户位次", required = true) @RequestParam Integer userRank,
            @Parameter(description = "学校UUID", required = true) @RequestParam String schoolUuid,
            @Parameter(description = "专业名称", required = true) @RequestParam String majorName,
            @Parameter(description = "省份", required = true) @RequestParam String province,
            @Parameter(description = "年份", required = true) @RequestParam Integer year,
            @Parameter(description = "考试类型", required = true) @RequestParam String examType) {
        
        try {
            Double probability = majorRecommendationService.calculateMajorAdmissionProbability(
                    userRank, schoolUuid, majorName, province, year, examType);
            return success(probability);
        } catch (Exception e) {
            log.error("计算专业录取概率失败", e);
            return CommonResult.error(500, "计算失败：" + e.getMessage());
        }
    }

    @GetMapping("/determine-type")
    @Operation(summary = "判断推荐类型")
    @PreAuthorize("@ss.hasPermission('system:major-recommendation:query')")
    public CommonResult<String> determineRecommendationType(
            @Parameter(description = "录取概率", required = true) @RequestParam Double probability) {
        
        try {
            String type = majorRecommendationService.determineRecommendationType(probability);
            return success(type);
        } catch (Exception e) {
            log.error("判断推荐类型失败", e);
            return CommonResult.error(500, "判断失败：" + e.getMessage());
        }
    }

    @PostMapping("/generate-reason")
    @Operation(summary = "生成专业推荐理由")
    @PreAuthorize("@ss.hasPermission('system:major-recommendation:query')")
    public CommonResult<String> generateMajorRecommendationReason(
            @Parameter(description = "学校名称", required = true) @RequestParam String schoolName,
            @Parameter(description = "专业名称", required = true) @RequestParam String majorName,
            @Parameter(description = "录取概率", required = true) @RequestParam Double probability,
            @Parameter(description = "推荐类型", required = true) @RequestParam String type,
            @Parameter(description = "专业标签") @RequestParam(required = false) List<String> majorTags) {
        
        try {
            String reason = majorRecommendationService.generateMajorRecommendationReason(
                    schoolName, majorName, probability, type, majorTags);
            return success(reason);
        } catch (Exception e) {
            log.error("生成专业推荐理由失败", e);
            return CommonResult.error(500, "生成失败：" + e.getMessage());
        }
    }

    @GetMapping("/calculate-rank")
    @Operation(summary = "根据分数计算位次")
    @PreAuthorize("@ss.hasPermission('system:major-recommendation:query')")
    public CommonResult<Integer> calculateRankByScore(
            @Parameter(description = "分数", required = true) @RequestParam Integer score,
            @Parameter(description = "省份", required = true) @RequestParam String province,
            @Parameter(description = "年份", required = true) @RequestParam Integer year,
            @Parameter(description = "考试类型", required = true) @RequestParam String examType) {
        
        try {
            Integer rank = majorRecommendationService.calculateRankByScore(score, province, year, examType);
            return success(rank);
        } catch (Exception e) {
            log.error("计算位次失败", e);
            return CommonResult.error(500, "计算失败：" + e.getMessage());
        }
    }

    @GetMapping("/filter-majors")
    @Operation(summary = "根据选科要求筛选专业")
    @PreAuthorize("@ss.hasPermission('system:major-recommendation:query')")
    public CommonResult<List<String>> filterMajorsBySubjects(
            @Parameter(description = "选科组合", required = true) @RequestParam String subjects,
            @Parameter(description = "省份", required = true) @RequestParam String province,
            @Parameter(description = "年份", required = true) @RequestParam Integer year,
            @Parameter(description = "考试类型", required = true) @RequestParam String examType,
            @Parameter(description = "批次") @RequestParam(required = false) String batch) {
        
        try {
            List<String> subjectList = Arrays.asList(subjects.split(","));
            List<String> majors = majorRecommendationService.filterMajorsBySubjects(
                    subjectList, province, year, examType, batch);
            return success(majors);
        } catch (Exception e) {
            log.error("筛选专业失败", e);
            return CommonResult.error(500, "筛选失败：" + e.getMessage());
        }
    }

    @GetMapping("/major-tags")
    @Operation(summary = "获取专业标签")
    @PreAuthorize("@ss.hasPermission('system:major-recommendation:query')")
    public CommonResult<List<String>> getMajorTags(
            @Parameter(description = "专业名称", required = true) @RequestParam String majorName,
            @Parameter(description = "学校UUID") @RequestParam(required = false) String schoolUuid) {
        
        try {
            List<String> tags = majorRecommendationService.getMajorTags(majorName, schoolUuid);
            return success(tags);
        } catch (Exception e) {
            log.error("获取专业标签失败", e);
            return CommonResult.error(500, "获取失败：" + e.getMessage());
        }
    }

    @GetMapping("/school-tags")
    @Operation(summary = "获取学校标签")
    @PreAuthorize("@ss.hasPermission('system:major-recommendation:query')")
    public CommonResult<List<String>> getSchoolTags(
            @Parameter(description = "学校UUID", required = true) @RequestParam String schoolUuid) {
        
        try {
            List<String> tags = majorRecommendationService.getSchoolTags(schoolUuid);
            return success(tags);
        } catch (Exception e) {
            log.error("获取学校标签失败", e);
            return CommonResult.error(500, "获取失败：" + e.getMessage());
        }
    }
}
